using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace Pokemon
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class Shop : DrawableGameComponent, ITappedInner
    {        
        #region Attribute

        List<Sprite> _sprites = new List<Sprite>();

        private PanelButton _shopPanel;

        private Chest _chest;

        private GameScreen _owner;

        private string _path;

        private bool _isClicked;

        private Vector2 _position;

        private TimeSpan _delayTime;

        private static int nDelay = 0;
#endregion
     
        /// <summary>
        /// 
        /// </summary>
        /// <param name="game"></param>
        /// <param name="fullPath"></param>
        public Shop(Game game, GameScreen owner, string fullPath, Vector2 position)
            : base(game)
        {
            _path = fullPath;

            _isClicked = false;

            _position = position;

            _owner = owner;

            Initialize();
        }

        public Chest Chest
        {
            get { return _chest; }
            set { _chest = value; }
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            XDocument doc = XDocument.Load(_path);
            XName name = XName.Get(@"Panel");
            Texture2D texture;
            int numFrame;
            var frameWidth = 0.0f;
            var frameHeight = 0.0f;
            var xCenterPoint = 0.0f;
            var yCenterPoint = 0.0f;
            string panelPath = "";//String chua duong dan dan den file dac ta cua panel trong Doi tuong shop
            if (doc.Document != null)
            {
                var definitions = doc.Document.Descendants(name);
                panelPath = definitions.First().Value;

                _shopPanel = new PanelButton(Game, _owner, panelPath);

                name = XName.Get(@"Definition");
                definitions = doc.Document.Descendants(name);                
                foreach (var definition in definitions)
                {
                    var xAttribute = definition.Attribute(@"SheetName");
                    if (xAttribute != null)
                    {
                        texture = Game.Content.Load<Texture2D>(xAttribute.Value);
                        
                        xAttribute = definition.Attribute(@"FrameWidth");
                        if (xAttribute != null)
                        {
                            frameWidth = float.Parse(xAttribute.Value);
                            xAttribute = definition.Attribute(@"FrameHeight");
                            if (xAttribute != null)
                            {
                                frameHeight = float.Parse(xAttribute.Value);
                            }
                        }

                        xAttribute = definition.Attribute(@"NumFrame");
                        numFrame = Int32.Parse(xAttribute.Value);

                        xAttribute = definition.Attribute(@"XCenterPoint");

                        xCenterPoint = float.Parse(xAttribute.Value);
                        xAttribute = definition.Attribute(@"YCenterPoint");

                        yCenterPoint = float.Parse(xAttribute.Value);

                        _sprites.Add(new Sprite(texture, numFrame, 
                                new Vector2(frameWidth, frameHeight), new Vector2(xCenterPoint, yCenterPoint), false));                     
                    }
                }
            }            
            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            _delayTime += gameTime.ElapsedGameTime;

            if (_delayTime.Milliseconds <= 50)
                return;
            nDelay++;

            _delayTime = TimeSpan.Zero;

            if (_isClicked)//Neu ma trong su kien user tap vao shop
            {
                _sprites[0].Update();                //thi tang frame hinh
                if (nDelay == 5)
                {
                    nDelay = 0;
                    _isClicked = false;
                    Clicked += BuyItem;
                    LayerManager layer = (LayerManager) Game.Services.GetService(typeof (LayerManager));
                    layer.SetPriorityThreshold(8);
                }
            }
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {            
            _sprites[0].Draw((SpriteBatch)Game.Services.GetService(typeof(SpriteBatch)), _position, Color.White);

            OnClicked(gameTime);

            base.Draw(gameTime);
        }

        #region Event: When user want to buy a item in shop

        public delegate void Click(GameTime gameTime);

        private event Click Clicked;

        private void OnClicked(GameTime gameTime)
        {
            Click handler = Clicked;
            if (handler != null) handler(gameTime);
        }

        private void BuyItem(GameTime gameTime)
        {
            LayerManager _layer = (LayerManager)Game.Services.GetService(typeof(LayerManager));
            _layer.Add(_shopPanel, 8);

            if (_chest != null)
            {
                _chest.OnShopOpened();
            }

            Clicked -= BuyItem;

            for (var i = 0; i < _shopPanel.Grid[0].Rows; i++)
                for (var j = 0; j < _shopPanel.Grid[0].Cols; j++)
                {
                    _shopPanel.Grid[0].Blanks[i,j].RemoveEvent();
                    _shopPanel.Grid[0].Blanks[i,j].AddFunc(BoughtItemProcessing);
                }

            _shopPanel.Grid[1].Blanks[0, 0].RemoveEvent();
            _shopPanel.Grid[1].Blanks[0, 0].AddFunc(Cancel);
            //            _shopPane.Draw(gameTime);
        }


        #endregion

        #region Event: When user bought item

        private void BoughtItemProcessing(object sender, Point p)
        {
            if (sender is Blank)
            {
                Blank b = sender as Blank;
                Card c = b.GetCard();
                if (_chest != null)
                    _chest.OnItemBought(c);
            }
        }

#endregion

        public bool CheckTapped(Point p)
        {
            Rectangle rect = new Rectangle((int)_position.X, (int)_position.Y, (int)_sprites[0].Size.X, (int)_sprites[0].Size.Y);
            var isTapped = rect.Contains(p);
            if (isTapped)
            {
                _isClicked = true;
                nDelay = 0;             
            }
            return isTapped;
        }

        /// <summary>
        /// Ham xu ly tinh huong khi user chon vao Let's Rock button, luc do blank se uy thac qua trinh xu ly cho Shop
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="p"></param>
        public void Cancel(object sender, Point p)
        {
            if (sender is Blank)
            {
                LayerManager layerManager = (LayerManager) Game.Services.GetService(typeof (LayerManager));
                layerManager.Remove(_shopPanel);
                if (_chest != null)
                    _chest.OnShopClosed();
                layerManager.SetPriorityThreshold(0);
            }
        }
    }
}

